<!--
* description: 备件销售收款
* author: xiaochengzuan
* createdDate: 2021-2-23
-->

<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :callback-obj="callbackObj"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      v-if="editPopupsVisible"
      :popups-visible.sync="editPopupsVisible"
      :popups-state="editPopupsState"
    />

    <detail
      :key="detailPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible.sync="detailPopupsVisible"
      :popups-state="editPopupsState"
    />
  </div>
</template>
<script>

import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import detail from './detail'
import Vue from 'vue'

import { orgApis } from '@/api/pa/salesManagementOfSparePartsInOutlets'

export default {
  name: 'SalesCollectionOfSpareParts',

  components: {
    OneTableTemplate,
    detail,
    Edit: () => import('./edit')
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // this.$refs['multipleTable'].data = [{bigAreaCode:'1'}]
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      editPopupsVisible: false,
      editPopupsVisibleDetail: false,
      editRowData: {},
      editRowDataDetail: {},
      // 网格查询API配置对象
      apiConfig: orgApis.salesCollectionOfSparePartssquery,

      detailPopupsKey: '1',
      detailRowData: {},
      detailPopupsVisible: false,

      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },        
        {
          compKey: 'btnKey3',
          size: 'small',
          name: 'confirm',
          clickEvent: this.add,
          text: '收款',
          position: 'right',
          disabled: true
        },
        {
          compKey: 'btnKey50',
          size: 'small',
          name: 'Error',
          clickEvent: this.toViod,
          text: '作废',
          position: 'right',
          disabled: true
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right'
        },
        {
          compKey: 'btnKey4',
          size: 'small',
          // clickEvent: () => this.batchDelete(),
          // clickEvent: this.add,
          text: '打印',
          name: '',
          position: 'left'
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [

            {
              compKey: 'compKey5',
              labelName: '客户性质：',
              codeField: 'customerType',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '1', statusText: '直营店' },
                { statusId: '2', statusText: '授权店' },
                { statusId: '0', statusText: '一般客户' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey1',
              labelName: '销售单号：',
              codeField: 'saleOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '客户名称：',
              codeField: 'customerName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },

            {
              compKey: 'compKey3',
              labelName: '销售类型：',
              codeField: 'saleType',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'saleType,saleTypeCn',
              options: [
                { saleType: '0', saleTypeCn: '常规销售' },
                { saleType: '1', saleTypeCn: '呆滞件销售' },
                { saleType: '2', saleTypeCn: '商场订单' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '收款状态：',
              codeField: 'settlementStatus',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '0', statusText: '未结算' },
                { statusId: '1', statusText: '已结算' },
                { statusId: '2', statusText: '已结清' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey6',
              labelName: '制单人：',
              codeField: 'dlrMakerId',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey7',
              labelName: '制单日期：',
              codeField: 'createdDate',
              component: () => import('@/components/org/datePicker/andtDatePicker'),
              type: 'andtDatePicker',
              isMul: false,
              isMust: false
            }
            //   {
            //   compKey: 'compKey4',
            //   labelName: '所属期间：',
            //   codeField: 'bigAreaName3',
            //   component: () => import('@/components/org/datePicker/andtDatePicker'),
            //   type: 'andtDatePicker',
            //   isMul: false,
            //   isMust: true
            // },
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'releaseId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'controlBtn1',
              label: '销售单号',
              width: 140,
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey1',
                  codeField: 'saleOrderCode',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.detail(index)
                }
              ]
            },
            {
              prop: 'customerTypeCn',
              label: '客户性质',
              hidden: false
            },
            {
              prop: 'saleTypeCn',
              label: '销售类型'
            },
            {
              prop: 'customerName',
              label: '客户名称'
            },
            {
              prop: 'customerPhone',
              label: '联系电话',
              width: 140
            },
            {
              prop: 'saleAmount',
              label: '销售总金额'
            },
            {
              prop: 'actualAmount',
              label: '已收金额'
            },
            {
              prop: 'notReceivableAmount',
              label: '待收金额'
            },
            {
              prop: 'empName',
              label: '制单人'
            },
            {
              prop: 'createdDate',
              label: '制单日期',
              width: 140
            },
            {
              prop: 'settlementStatusCn',
              label: '结算状态'
            },
            {
              prop: 'remark',
              label: '备注',
              hidden: true
            }
          ],

      // 表单查询数据
      formField: this.$utils.getFormField(this, {
        payType:'1',
        customerType: '',
        saleOrderCode: '',
        customerName: '',
        saleType: '',
        settlementStatus: '',
        dlrMakerId: '',
        createdDate: '',
        updateControlId: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode]),

      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectData = selection
          this.handleSelectionChange(selection)
        }
      }
    }
  },

  mounted() {
    // 列表查询
    this.queryTable(1)
  },

  methods: {
    detail(index) {
      this.editPopupsState = 'edit'
      this.detailPopupsVisible = true
      this.editRowData = this.$utils.deepCopy(this.$refs['multipleTable'].list[index])
      console.log(this.editRowData)
    },
    toViod(){
      const that = this
      if(!this.selectData.length){
        this.$message({
          message:'请选择数据进行作废!',
          type:'warning',
          duration:2000
        })
        return
      }
      this.$confirm('此操作将作废选择数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const queryList = {list: []}
          queryList.list = this.selectData
          const queryObj = {
            type: 'mutation',
            // api配置
            apiConfig: orgApis.updateStatus,
            variables: queryList
          }
          let paramD = this.$getParams(queryObj)
          this.$requestAPI(paramD).then(response => {
            if (response.result === '1') {
              that.queryTable(1)
              that.$message({
                message:'作废成功!'
              })
            } else {
              that.$message({
                message:response.msg
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });      
      
      // api:updateStatus,
    },
    // 点击收款
    add() {
      if(this.selectData.length != 1){
        this.$message({
          message:'只能选择一条数据进行收款!',
          type:'warning',
          duration:2000
        })
        return
      }
      const that = this
      const queryObj = {
        type: 'mutation',
        // api配置
        apiConfig: orgApis.queryPartSaleOrderAmount,
        variables: {
          saleOrderId: that.selectData[0].saleOrderId,
          updateControlId: that.selectData[0].updateControlId
        }
      }
      var paramD = this.$getParams(queryObj)

      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.editRowData = response.rows[0]
          this.editPopupsState = 'add'
          this.editPopupsVisible = true
        }
      })
      
    },

    // 导出
    export() {
      var date = new Date()
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var day = date.getDate()
      month = (month < 10 ? '0' + month : month)
      day = (day < 10 ? '0' + day : day)
      var mydate = year.toString() + month.toString() + day.toString()
      const returnObj = {
        // api配置
        apiConfig: {
          APIUrl: '/mp/e3sh/basics/ve/CarTypeService/exportCarType.do'
        },
        variables: this.formField
      }
      returnObj.variables.dataType = 'excel'
      const paramD = this.$getParams(returnObj)
      this.$requestAPI(paramD).then(res => {
        this.$utils.downloadFile(res, `车系维护${mydate}.xlsx`)
      })
    },

    // 当选择项发生变化时会触发该t事件
    handleSelectionChange(selection) {
      const btns = this.tableButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    }
  }
}
</script>
